package com.wuming.caiwu.controller;

import com.wuming.caiwu.core.BusinessException;
import com.wuming.caiwu.core.CommonResult;
import com.wuming.caiwu.core.JsonResult;
import com.wuming.caiwu.model.*;
import com.wuming.caiwu.service.MemberService;
import com.wuming.caiwu.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hanfei on 16/4/19.
 */
@Controller
@RequestMapping("/web/syspermission")
public class SysPermissionController extends BaseController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private MemberService memberService;

    @RequestMapping(value = "/addSysPermission/{pid}", method = RequestMethod.GET)
    public String addSysPermission(@PathVariable Long pid,Model model) {
        model.addAttribute("pid",pid);
        return "/syspermission/editSysPermission";
    }

    @RequestMapping(value = "/manageSysPermission", method = RequestMethod.GET)
    public String manageSysPermission() {
        return "/syspermission/manageSysPermission";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult list(@RequestParam(required = false) String name,
                             @RequestParam(defaultValue = "0") int pageIndex, @RequestParam(defaultValue = "10") int pageSize){
        try {
            List<SysPermission> students = sysPermissionService.getSysPermissionsByPage(name, pageIndex, pageSize);
            int total = sysPermissionService.getTotal(name);
            return CommonResult.createSuccessResult(students, total, "查询商品信息成功.");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createFailureResult("查询商品信息失败.");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("查询商品信息失败.");
        }
    }

    @RequestMapping(value = "/editSysPermission/{id}", method = RequestMethod.GET)
    public String editStudent(Model model, @PathVariable Long id) {
        logger.info("准备修改商品信息ID:{}", id);
        SysPermission permission = sysPermissionService.getSysPermissionById(id);
        model.addAttribute("permission", permission);
        model.addAttribute("pid", permission.getPid());
        return "/syspermission/editSysPermission";
    }

    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public JsonResult save(SysPermission product) {
        try {
            if (null != product.getId()) {
                sysPermissionService.modifySysPermission(product);
            } else {
                sysPermissionService.saveSysPermission(product);
            }
        } catch (Exception e) {
            logger.error("保存商品信息失败,失败信息:{}", e.getMessage());
            return new JsonResult<Object>(null, "保存商品基本信息失败", false);
        }
        return new JsonResult<Object>(product.getId(), "保存商品基本信息成功.", true);
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public CommonResult delete(@PathVariable Long id) {
        logger.info("准备删除菜单信息ID:{}", id);
        try {
            sysPermissionService.removeSysPermissionById(id);
            return CommonResult.createSuccessResult("删除菜单信息成功.");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createFailureResult("删除菜单信息失败.");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("删除菜单信息失败.");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/updateRolePermission", method = RequestMethod.POST)
    public CommonResult updateRolePermission(@RequestParam Long roleId,@RequestParam String checkedData) {
        logger.info("准备更新角色ID:{}的权限", roleId);
        try {
            sysPermissionService.removePermissionByRoleId(roleId);
            sysPermissionService.saveRolePermission(roleId,checkedData);
            return CommonResult.createSuccessResult("更新角色权限信息成功.");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createFailureResult("更新角色权限信息失败.");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("更新角色权限信息失败.");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getUserPermission", method = RequestMethod.GET)
    public CommonResult getUserPermission(@RequestParam Long userId) {
        logger.info("准备获取用户ID:{}的权限", userId);
        try {
            List<SysPermission> permissions = sysPermissionService.getPermissionByUserId(userId);
            return CommonResult.createSuccessResult(permissions,permissions.size(),"查询用户权限成功.");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createFailureResult("准备获取用户信息失败.");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("准备获取用户信息失败.");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getRolePermission/{roleId}", method = RequestMethod.GET)
    public CommonResult getRolePermission(@PathVariable Long roleId,@RequestParam Integer storeId) {
        logger.info("准备查询角色ID:{}的权限", roleId);
        try {
            List<SysRolePermissionMenu> menus = new ArrayList<>();
            Member current = memberService.getMemberById(storeId);
            List<SysPermission> permissions = null;
            if(memberService.isAdministrator(current)){
                permissions = sysPermissionService.getSysPermission(0L);
                for (SysPermission permission: permissions
                ) {
                    SysRolePermissionMenu menu = new SysRolePermissionMenu();
                    menu.setId(permission.getId());
                    menu.setTitle(permission.getName());
                    menu.setSpread(true);
                    menu.setChecked(false);
                    List<SysPermission> childPermissions = sysPermissionService.getSysPermission(permission.getId());
                    List<SysRolePermissionMenu> childMenus = new ArrayList<>();
                    if(null != childPermissions && !childPermissions.isEmpty()){
                        for (SysPermission sp: childPermissions
                        ) {
                            SysRolePermissionMenu childMenu = new SysRolePermissionMenu();
                            childMenu.setId(sp.getId());
                            childMenu.setTitle(sp.getName());
                            childMenu.setSpread(true);
                            childMenu.setChecked(false);
                            childMenus.add(childMenu);
                        }
                    }
                    menu.setChildren(childMenus);
                    menus.add(menu);
                }
            }else{
                permissions = sysPermissionService.getPermissionByRoleId(current.getRole().longValue());
                Map<String,List<SysRolePermissionMenu>> permissionMap = new HashMap<>();
                for (SysPermission permission: permissions
                ) {
                    if(permission.getPid() == 0){
                        SysRolePermissionMenu menu = new SysRolePermissionMenu();
                        menu.setId(permission.getId());
                        menu.setTitle(permission.getName());
                        menu.setSpread(true);
                        menu.setChecked(false);
                        menus.add(menu);
                    }else{
                        Long pid = permission.getPid();
                        List<SysRolePermissionMenu> childMenus = permissionMap.get(pid.toString());
                        if(null == childMenus){
                            childMenus = new ArrayList<>();
                            SysRolePermissionMenu menu = new SysRolePermissionMenu();
                            menu.setId(permission.getId());
                            menu.setTitle(permission.getName());
                            menu.setSpread(true);
                            childMenus.add(menu);
                        }else{
                            SysRolePermissionMenu menu = new SysRolePermissionMenu();
                            menu.setId(permission.getId());
                            menu.setTitle(permission.getName());
                            menu.setSpread(true);
                            childMenus.add(menu);
                        }
                        permissionMap.put(pid.toString(),childMenus);
                    }
                }
                for (SysRolePermissionMenu menu: menus
                     ) {
                    List<SysRolePermissionMenu> childMenus = permissionMap.get(menu.getId().toString());
                    menu.setChildren(childMenus);
                }
            }
            List<SysPermission> rolePermissions = sysPermissionService.getPermissionByRoleId(roleId);
            Map<String,Object> result = new HashMap<>();
            result.put("allMenus",menus);
            result.put("rolePermissions",rolePermissions);
            return CommonResult.createSuccessResult(result,result.size(),"查询系统菜单成功.");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createFailureResult("删除菜单信息失败.");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("删除菜单信息失败.");
        }
    }


    @RequestMapping(value="/treedata")
    @ResponseBody
    public Object list(){
        List<SysPermission> permissions = sysPermissionService.getSysPermission(0L);
        List<SysPermission> results = sysPermissionService.buildSysPermission(permissions);
        List<TbMenu> list = new ArrayList<>();
        for (SysPermission permission: results
             ) {
            TbMenu menu = new TbMenu();
            menu.setId(permission.getId());
            menu.setName(permission.getName());
            menu.setUrl(permission.getUri());
            menu.setPid(permission.getPid());
            menu.setType(permission.getType());
            menu.setValue(permission.getValue());
            menu.setSex(permission.getIcon());
            list.add(menu);
        }
//        TbMenu menu = new TbMenu();
//        menu.setId(1);
//        menu.setName("系统配置");
//        menu.setSex("1");
//        menu.setUrl("/user");
//        menu.setPid(0);
//        list.add(menu);
//        TbMenu menu1 = new TbMenu();
//        menu1.setId(2);
//        menu1.setName("角色配置");
//        menu1.setSex("2");
//        menu1.setUrl("/user/111");
//        menu1.setPid(1);
//        list.add(menu1);
        return new TreeTableModel(list);
    }
}
